package com.xzmzhp.security;

import com.xzmzhp.constant.ReturnConstant;
import com.xzmzhp.utils.return_tool.ReturnData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author: 王源(xm)
 * @create: 2021-06-01 10:45
 * @program: ams
 * @description: 登录逻辑处理类
 */

@Component
public class LoginService {

    @Autowired
    public TokenManager tokenManager;

    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录信息
     */
    public ReturnData login(String username, String password) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            return ReturnData.error(ReturnConstant.FAIL, "用户名密码错误");
        }
        //获取用户信息
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //添加token信息
        loginUser.setToken(tokenManager.createToken(loginUser));
        return ReturnData.ok(loginUser);
    }
}
